package com.littleken.foodieCommon.Utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/*
 * Create by littleken on 2020/11/23 15:21
 */
public class SerializeUtil {

    private static final String DATE_TIME_PATTERN2 = "yyyy-MM-dd HH:mm:ss";

    private static ObjectMapper objectMapper = null;

    public SerializeUtil() {

    }

    public static ObjectMapper get() {
        if (objectMapper == null) {
            objectMapper = createObjectMapper();
        }
        return objectMapper;
    }

    private static ObjectMapper createObjectMapper(SimpleDateFormat des, SimpleDateFormat ser) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_PATTERN2));
        // 因为objectmapper默认是使用UTC时间，但是我们创建的时间是使用默认时区
        objectMapper.setTimeZone(TimeZone.getDefault());
        return objectMapper;
    }

    /**
     * 默认使用yyyy-MM-dd HH:mm:ss序列化和反序列化日期
     *
     * @return
     */
    private static ObjectMapper createObjectMapper() {
        SimpleDateFormat dateTimeSdf2 = new SimpleDateFormat(DATE_TIME_PATTERN2);
        return createObjectMapper(dateTimeSdf2, dateTimeSdf2);
    }

    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return get().getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    public static void writeResponse(HttpServletResponse response, Object data) {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            Writer writer = response.getWriter();
            writer.write(get().writeValueAsString(data));
            writer.flush();
            writer.close();
        } catch (IOException ignored) {

        }
    }
}
